<?php

/*------------------------------------------------
*
*   Explay Engine Content Management System.
*   Copyright © 2008 Golovdinov Alexander.
*
*-------------------------------------------------
*
*   Official site: wwww.alex-home.spb.ru/explay.html
*   Contact e-mail: golovdinov@gmail.com
*
*   GNU General Public License original source:
*   http://www.gnu.org/licenses/gpl-3.0.html
*
------------------------------------------------*/

if (!defined ('EXPLAY')) exit;


class userModelArticles implements iUserModelArticles {

	public $errors = array ();

	private static $instance = false;
	public static function getInstance () {
		if (self::$instance === false) self::$instance = new userModelArticles;
			
		return self::$instance;
	}
	
	private function __construct () {}

	/**
	 * Редактирование статьи
	 */
	public function edit_article () {
		
		$controller = articlesController::getInstance ();
		$mysql = articlesMySQL::getInstance ();
		$db = MySQL::getInstance ();
		$view = new userViewArticles;
		
		$get = $mysql->db_select_article ($controller->options_str);
	
		if ($db->num_rows ($get) == 0) error_404 ();
				
		$art = $db->fetch_array ($get);
			
		CORE::set_page_title ('Изменить статью &mdash; '.CORE::$SITE['site_name']);
			
		$controller->set_data ($view->article_form ($art));
		
		unset ($controller, $mysql, $db, $view);
	}
	
	/**
	 * Удаление статьи
	 */
	public function delete_article () {
		$controller = articlesController::getInstance ();
		$mysql = articlesMySQL::getInstance ();
		
		$mysql->delete_article ($controller->options_str);
		
		$controller->set_message ('Статья удалена!');
		
		unset ($mysql, $controller);
	}
	
	/**
	 * Добавление статьи
	 */
	public function add_article () {
		$controller = articlesController::getInstance ();
		$view = new userViewArticles;
		
		$art = array (
			"art_id" => "0",
			"art_category" => "",
			"art_header" => "",
			"art_body" => "",
			"art_author" => "",
			"art_date" => "",
			"art_comments" => "on",
			"art_url_name" => "",
			"art_image" => "",
			"art_publik" => "yes",
			"art_like_page" => "no",
			"art_visible" => "on",
			"art_tags" => "",
			"art_rating" => "",
			"art_voters" => "",
			"art_community" => "",
			"auto_tag" => "yes"
		);
		
		$controller->set_data ($view->article_form ($art));
		
		unset ($controller, $view);
	}
	
	/**
	 * Сохранение статьи
	 */
	public function save_article () {
		
		$controller = articlesController::getInstance ();
		$mysql = articlesMySQL::getInstance ();
		$db = MySQL::getInstance ();
		
		$art = array ();
		
		$allowed_tags = array ("a","p","h1","h2","h3","h4","h5","h6","blockquote","i","em","b","strong","u","ul","ol","li","sup","table","tr","td","s","strike","font","img","nobr","abbr","acronym","pre","code","br","cut","youtube", "rutube", "vimeo");
		$allowed_string = '';
		foreach ($allowed_tags as $tag) $allowed_string .= '<'.$tag.'>';
		
		$art['art_header'] = (string) strip_tags ($_POST['header']);
		$art['art_body'] = (string) strip_tags ($_POST['big_text'], $allowed_string);
		$art['art_body'] = replace_symbols ($art['art_body']);
		$art['art_body'] = clear_danger_html ($art['art_body']);
		
		(isset($_POST['auto_tag'])) ? $art['auto_tag'] = 'yes' : $art['auto_tag'] = "no";
		(isset($_POST['comment'])) ? $art['art_comments'] = "on" : $art['art_comments'] = "off";
		
		$art['art_category'] = (string) addslashes ($_POST['category']);
		$art['art_tags'] = (string) trim (strip_tags ($_POST['tags']));
		$art['art_tags'] = htmlspecialchars ($art['art_tags'], ENT_QUOTES);
		
		if (substr($art['art_tags'], mb_strlen($art['art_tags'])-1) == ',') $art['art_tags'] = substr($art['art_tags'], 0, mb_strlen($art['art_tags'])-1);
		
		if ($controller->settings['public_now'] == 'on')
			$art['art_visible'] = (urldecode ($_POST['action_type']) == 'опубликовать') ? 'on' : 'off';
		else
			$art['art_visible'] = 'off';
			
		$id = intval ($_POST['tid']);
		
		if ($id == 0) {
			
			$art['art_publik'] = ($controller->settings['public_to_mainpage'] == 'on') ? 'yes' : 'no';
			
			$timer = $db->num_rows ($db->query ("SELECT * FROM ".DB_PEREFIX."_articles WHERE art_author = '".$art['art_author']."' AND art_date > '".(time() - 250)."'"));
			$today = $db->num_rows ($db->query ("SELECT * FROM ".DB_PEREFIX."_articles WHERE art_author = '".$art['art_author']."' AND art_date > '".(time() - (60 * 60 * (date("H")) + ( 60 * date("i"))  ))."'"));
				
			if ($timer > 0) $controller->set_error ('Подождте, пожалуйста, 4 минуты!');
			if ($today >= 10) $controller->set_error ('Вы не можете добавлять за день более 10 статей!');
			
			if ($controller->settings['personal_blog'] == 'off') {
				$check_blog = $db->num_rows ($db->query ("SELECT * FROM ".DB_PEREFIX."_art_category WHERE cat_name = '".$art['art_category']."'"));
				if ($check_blog == 0) $this->errors['blog'] = 'Нет такого блога!';
			}
		
		} else {
			
			$options = (is_admin() || is_moderator())
				? ''
				: "AND art_author = ".User::$properties['user_id'];
			
			$check = (int) $db->num_rows ($db->query ("SELECT * FROM ".DB_PEREFIX."_articles WHERE art_id = $id $options"));
			if ($check == 0) $controller->set_error ('Нет такой статьи!');
			
		}
		
		
		if ($art['art_category'] != '' && $controller->settings['write_to_public'] > my_karma()) $this->errors['blog'] = 'У Вас слишком низкая карма, чтобы писать в публичный блог!';
		if ($art['art_header'] == '') $this->errors['header'] = 'Заполните заголовок статьи';
		if ($art['art_body'] == '') $this->errors['text'] = 'Заполните текст статьи!';
		if ($art['art_category'] == '' && $controller->settings['personal_blog'] == 'off') $this->errors['blog'] = 'Выберитеы блог';
		if (mb_strlen ($art['art_header']) > 90) $this->errors['header'] = 'Слишком длинный заголовок';
		if (mb_strlen ($art['art_body']) > 15000) $this->errors['text'] = 'Слишком длинный текст';
		
		
		if (count ($controller->errors) == 0 && count ($this->errors) == 0) {
			$this->article_save_action ($art, $id);			
		}
		
		unset ($controller, $mysql, $db, $art);
	}
	
	/**
	 */
	private function article_save_action ($art, $id) {
		$mysql = articlesMySQL::getInstance ();
		$controller = articlesController::getInstance ();
		
			// Если id статьи равен 0, то создаем новую статью
			if ($id == 0) {
					
				$mysql->add_article ($art);
				
				$controller->set_message ('Статья добавлена!');	
				
				if	 (file_exists ($_SERVER['DOCUMENT_ROOT'].'/include/cache/tags.php')) unlink ($_SERVER['DOCUMENT_ROOT'].'/include/cache/tags.php');
				if	 (file_exists ($_SERVER['DOCUMENT_ROOT'].'/include/cache/last_publish.php')) unlink ($_SERVER['DOCUMENT_ROOT'].'/include/cache/last_publish.php');
						
				if ($controller->settings['public_now'] == 'on') redirect ('/articles/'.mysql_insert_id().'.html');	
					
			// Если id статьи задан, то обновляем сатью
			} else {
				
				$update = $mysql->save_article ($art, $id);
				$controller->set_message ('Статья сохранена!');
				
				if ($controller->settings['public_now'] == 'on') redirect ("/articles/$id.html");
			}
		
		unset ($mysql, $controller, $db);
	}
	
	/**
	 * Редактирование блога
	 */
	 public function edit_blog () {
	 	$controller = articlesController::getInstance ();
		$mysql = articlesMySQL::getInstance ();
		$db = MySQL::getInstance ();
		$view = new userViewArticles;
		
		$get = $mysql->select_blog ($controller->options_str);
	
		if ($db->num_rows ($get) == 0) error_404 ();
				
		$blog = $db->fetch_array ($get);
		
		CORE::set_page_title ('Изменить блог &mdash; '.CORE::$SITE['site_name']);
			
		$controller->set_data ($view->blog_form ($blog));
		
		unset ($controller, $mysql, $db, $view);
	 }
	
	/**
	 * Сохранение блога
	 */
	public function save_blog () {
		
		$controller = articlesController::getInstance ();
		$mysql = articlesMySQL::getInstance ();
		$db = MySQL::getInstance ();
		
		$blog = array ();
		
		$blog['cat_name'] = addslashes (strip_tags ($_POST['name']));
		$blog['cat_header'] = addslashes (strip_tags ($_POST['header']));
		$blog['cat_description'] = addslashes (strip_tags ($_POST['desc']));
		$id = intval ($_POST['tid']);
		
		if ($blog['cat_header'] == '') $this->errors['blogheader'] = 'Заполните название блога!';
		
		if ($id == 0) {
			if (!preg_match("#^[a-z0-9_]{3,16}+$#", $blog['cat_name'])) $this->errors['blogname'] = 'Имя блога незаполнено или не соответствует формату!';
			
			$today = $db->num_rows ($db->query ("SELECT * FROM ".DB_PEREFIX."_art_category WHERE cat_author = '".User::$properties['user_id']."' AND cat_date > '".(time() - (60 * 60 * (date("H")) + ( 60 * date("i"))  ))."'"));
			$clone = $db->num_rows ($db->query ("SELECT * FROM ".DB_PEREFIX."_art_category WHERE cat_name = '".$blog['cat_name']."'"));
			
			if ($today > 0 && !is_admin() && !is_moderator()) $controller->set_error ('Вы не можете создавать более одного блога в день!');
			if ($clone > 0) $this->errors['blogname'] = 'Блог с таким именем уже существует!';
			
			if (!is_admin() && my_karma() < $controller->settings['new_blog_karma']) $controller->set_error ('У Вас слишком маленькая карма, чтобы создавать блог!');
	
		} else {
			if (!is_admin() && !is_moderator()) {
				$check = $db->num_rows ($db->query ("SELECT * FROM ".DB_PEREFIX."_art_category WHERE cat_author = '".User::$properties['user_id']."' AND cat_id = '$id'"));
				if ($check != 1) $controller->set_error ('Вы, наверное, ошиблись. У Вас нет такого блога.');
			}
		}
		
		if ($_FILES['avatar']['name'] != '' && eregi('[A-Za-z0-9]\.(jpeg|jpg|gif|png|bmp|JPEG|JPG|GIF|PNG|BMP)', $_FILES['avatar']['name'])) {
			if (copy($_FILES['avatar']['tmp_name'], $_SERVER['DOCUMENT_ROOT'].'/include/cache/'.$_FILES['avatar']['name'])) {
				
				include $_SERVER['DOCUMENT_ROOT'].'/engine/image.class.php';
				try {
					$image = new imageResize (
							$_SERVER['DOCUMENT_ROOT'].'/include/cache/'.$_FILES['avatar']['name'],
							$blog['cat_name'],
							'images/blogs',
							array(75,75),
							false,
							80
						);
					$image->resize ();
				}
				catch (Exception $e) {
					$this->errors['file'] = $e->getMessage();
				}
			} else {
				$this->errors['file'] = 'Ошибка загрузки файла!';
			}
		}
		
		if (count ($controller->errors) == 0 && count ($this->errors) == 0) {
			if ($id == 0) {
				$mysql->add_blog ($blog);
				$controller->set_message ('Блог создан!');
			} else {
				$mysql->save_blog ($blog['cat_header'], $blog['cat_description'], $id);
				$controller->set_message ('Блог сохранен!');
				
				redirect ("/articles/".$blog['cat_name']."/");
			}
		}
		
		unset ($controller, $mysql, $db, $blog);
	}
	
	/**
	 * Добавление блога
	 */
	public function add_blog () {
		$controller = articlesController::getInstance ();
		$view = new userViewArticles;
		
		$blog = array (
			'cat_id' => '0',
			'cat_name' => '',
			'cat_header' => '',
			'cat_description' => '',
			'cat_rating' => '',
			'cat_voters' => '',
			'cat_date' => '',
			'allow_users' => '',
			'cat_author' => ''
		);
		
		$controller->set_data ($view->blog_form ($blog));
		
		unset ($comtroller, $view);
	}
	
	/**
	 * Удаление блога? 0_o
	 */
	/*public function delete_blog () {
		$controller = articlesController::getInstance ();
		$mysql = articlesMySQL::getInstance ();
		
		$mysql->delete_blog ($controller->options_str);
		
		$controller->set_message ('Блог удален!');
		
		unset ($mysql, $controller);
	}*/


}